<template>
	<view class="login-container">
		<!-- 图片 -->
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<!-- 登录按钮 -->
		<button type="primary" class="btn-login" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button>
		<!-- 文本 -->
		<view class="login-text">登录后尽享更多权益</view>
	</view>
</template>

<script>
	import {
		mapMutations,
		mapState
	} from 'vuex'
	export default {
		name: "my-login",
		data() {
			return {};
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'saveSkipCart']),
			// 获取用户信息(uniapp文档中查看open-type有效值)
			getUserInfo(e) {
				// 判断是否获取用户信息成功
				if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权！')

				// 获取用户信息成功， e.detail.userInfo 就是用户的基本信息
				this.updateUserInfo(e.detail.userInfo)
				this.getToken(e.detail)
				this.skipSettle()
			},

			// 获取登录成功后的 Token 字符串
			async getToken(info) {
				// 调用微信登录接口
				const [err, res] = await uni.login().catch(err => err)
				// 判断是否 uni.login() 调用失败
				if (err || res.errMsg !== 'login:ok') return uni.$showMsg('登录失败！')
				// 准备参数对象
				const query = {
					code: res.code,
					encryptedData: info.encryptedData,
					iv: info.iv,
					rawData: info.rawData,
					signature: info.signature
				}
				const res2 = await uni.$http.post('/api/public/v1/users/wxlogin', query)
				// 由于接口有问题 所以获取不到token的值
				// 所以就由我定义一个假token
				// if (res2.data.meta.status !== 200) return uni.$showMsg('登录失败！')
				const new_token =
					'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
				uni.$showMsg('登录成功', 1500)
				this.updateToken(new_token)
			},

			// 自动跳转到结算页面
			skipSettle() {
				if (this.skipMethod !== 'switchTab') return
				uni.switchTab({
					url: this.skipUrl
				})
				// 将仓库里的数据清空
				this.saveSkipCart([null, null])
			}
		},
		computed: {
			...mapState('m_user', ['skipMethod', 'skipUrl'])
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f8f8f8;
	}

	.login-container {
		height: 750rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: #f8f8f8;
		position: relative;
		overflow: hidden;

		.btn-login {
			width: 90%;
			background-color: #be0000;
			border-radius: 50px;
			margin-top: 10px;
			margin-bottom: 15px;
		}

		.login-text {
			font-size: 12px;
			color: gray;
		}
	}
</style>